/**
 * @brief 
 * 
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sys/stat.h"
#include "stdint.h"
#include "crc32.h"


struct output_cfg_s
{
    unsigned char filenamef;
    unsigned char filesizef;
};

struct output_cfg_s output_cfg;
/**
 * @brief cal_crc32
 *
 * @param file
 * @return int
 */
int cal_crc32(char* file)
{
    FILE* fp = NULL;
    unsigned char* pbuf = NULL;
    uint32_t crc = 0;
    struct stat st;

    if (stat(file, &st) != 0)
    {
        printf("stat file error\n");
    }
    fflush(stdout);

    pbuf = (unsigned char*)malloc(st.st_size);
    if (pbuf != NULL)
    {
        fp = fopen(file, "rb");
        if (fp != NULL)
        {
            fread(pbuf, 1, st.st_size, fp);
            crc = CRC32Software(pbuf, st.st_size);
            if (output_cfg.filenamef)
            {
                printf("[%s] ", file);
            }
            if (output_cfg.filesizef)
            {
                printf("[%ld] ", st.st_size);
            }
            printf("0x%08x\n", crc);
            fclose(fp);
        }
        else
        {
            printf("open file error %s\n", file);
        }

        free(pbuf);
    }
    else
    {
        printf("malloc error [%ld]\n", st.st_size);
    }

    return 0;
}


/**
 * @brief runparam
 * 
 * @param argc 
 * @param arg 
 * @return int 
 */
int runparam(int argc, char* arg[])
{
    int i = 0;

    output_cfg.filenamef = 0;
    output_cfg.filesizef = 0;


    if (argc < 1)
    {
        return -1;
    }

    for (i = 1; i < argc; i++)
    {
        /* help */
        if (!strcmp("--help", *(arg + i)))
        {
            printf("** help infomation **\n");
            printf(" cal file crc32 \n");
            printf(" -f output with file name\n");
            printf(" -s output with file size\n");
            printf("** end **");
            continue;
        }

        if (!strcmp("-f", *(arg + i)))
        {
            output_cfg.filenamef = 1;
            continue;
        }

        if (!strcmp("-s", *(arg + i)))
        {
            output_cfg.filesizef = 1;
            continue;
        }

        /* file */
        cal_crc32(*(arg + i));
    }

    return 0;
}


/**
 * @brief main function
 * 
 * @param argc 
 * @param arg 
 * @return int 
 */
int main(int argc, char* arg[])
{
    runparam(argc, arg);

    return 0;
}
